package phone_dao

import (
	"errors"
	"hft/Database/admin"
	"hft/Database/admin/message"
	"hft/Database/admin/user_db"
	"hft/Http/Services/new_clue/clue_dao"
	"hft/e"
	"hft/global"
	"hft/tools"
	"time"

	"gorm.io/gorm"
)

func FindUser(data *user_db.PhoneRecord, city int, db *gorm.DB) (customer *user_db.User, err error) {
	var user *user_db.User
	if err := global.OC_DB.Where("phone = ? AND city = ?", data.CallingID, city).First(&user).Error; err != nil {

		return nil, err
	} else {
		return user, err
	}
}

func CreateUser(data *user_db.PhoneRecord, city int, db *gorm.DB) (err error) {
	var uuid = tools.GenUUID2()
	var louID int
	// 找出分机号对应的楼盘
	var lou string
	louPan, err := FindLou(data.Extension, global.OC_DB)
	if err != nil {
		// 楼盘不存在就默认为空
		lou = ""
		louID = 0
	} else {
		lou = louPan.Name
		louID = int(louPan.ID)
	}

	var release_time = clue_dao.FindCityTimeConfig(city)
	var user = map[string]interface{}{
		"create_time":   time.Now(),
		"update_time":   time.Now(),
		"uuid":          uuid,
		"phone":         data.CallingID,
		"city":          city,
		"intend_lou":    lou,
		"intend_lou_id": louID,
		"is_valid":      1,
		"manager_id":    0,
		"release_time":  release_time,
		"show":          0,
		"file":          0,
		"tag":           0,
	}
	// 是否接听，接通了就直接分配不进入公客池
	if data.RecStatus == "1" {
		// 找出对应的broker
		broker, err := FindBroker(db, data.CalledID)
		if err == nil {
			user["manager_id"] = broker.ID
			user["manager_name"] = broker.RealName
			user["history_manager_num"] = 1
			user["newest_clue_time"] = time.Now()
			db.Transaction(func(tx *gorm.DB) error {
				db.Model(&user_db.User{}).Create(&user)
				var newUser *user_db.User
				db.Where("phone = ?", data.CallingID).First(&newUser)
				var newClue = &user_db.Clue{
					UserID:       newUser.ID,
					LouPanID:     louID,
					Port:         6,
					OriginType:   3,
					PhoneRecord:  *data,
					ActivityName: "400来电",
				}
				db.Create(&newClue)
				var NowMessage = e.GetCustomer(broker.RealName)
				// 创建跟进
				var follow = map[string]interface{}{
					"user_id":           newUser.ID,
					"create_time":       time.Now(),
					"cont":              NowMessage.Cont,
					"is_system_message": 1,
				}
				var systemMessage = &message.SysMessage{
					SysTitle: NowMessage.Title,
					SysCont:  NowMessage.Cont,
					UserID:   newUser.ID,
				}
				db.Create(&systemMessage)
				db.Model(user_db.FollowUp{}).Create(&follow)
				return nil
			})
		}
	} else {
		db.Transaction(func(tx *gorm.DB) error {
			db.Model(&user_db.User{}).Create(&user)
			var newUser *user_db.User
			db.Where("phone = ?", data.CallingID).First(&newUser)
			var newClue = &user_db.Clue{
				UserID:       newUser.ID,
				LouPanID:     int(louPan.ID),
				Port:         6,
				OriginType:   3,
				PhoneRecord:  *data,
				ActivityName: "400来电",
			}
			db.Create(&newClue)
			return nil
		})
	}
	return nil
}

// 找出分机号
func FindLou(dn string, db *gorm.DB) (info *admin.LouPan, err error) {
	var lou *admin.LouPan
	if err = db.Joins("SellLouPanInfo").Where("`SellLouPanInfo`.`sell_phone` = ?", dn).First(&lou).Error; err != nil {
		return nil, errors.New(e.LouPanNotExist)
	} else {
		return lou, nil
	}
}

// 找出经办经纪人
func FindBroker(db *gorm.DB, broker_phone string) (info *admin.Account, err error) {
	var broker *admin.Account
	if err = db.Where("phone = ?", broker_phone).First(&broker).Error; err != nil {
		return nil, errors.New(e.AccountNotExist)
	} else {
		return broker, nil
	}
}

// 添加记录
func AddClue(db *gorm.DB, user *user_db.User, data *user_db.PhoneRecord) {
	louPan, _ := FindLou(data.Extension, db)
	var clue = &user_db.Clue{
		UserID:       user.ID,
		LouPanID:     int(louPan.ID),
		Port:         6,
		OriginType:   3,
		PhoneRecord:  *data,
		ActivityName: "400来电",
	}
	db.Create(&clue)
}
